const path = require('path');
const dotenv = require('dotenv');

// 加载环境变量
const envFile = process.env.NODE_ENV === 'production' ? '.env.production' : 
                process.env.NODE_ENV === 'test' ? '.env.test' : '.env.development';

dotenv.config({ path: path.resolve(process.cwd(), envFile) });
dotenv.config({ path: path.resolve(process.cwd(), '.env') }); // 默认环境变量

// 验证必需的环境变量
const requiredEnvVars = [
  'DB_HOST',
  'DB_PORT', 
  'DB_NAME',
  'DB_USER',
  'JWT_SECRET',
  'SESSION_SECRET'
];

const missingEnvVars = requiredEnvVars.filter(envVar => !process.env[envVar]);
if (missingEnvVars.length > 0) {
  throw new Error(`缺少必需的环境变量: ${missingEnvVars.join(', ')}`);
}

const config = {
  // 应用配置
  app: {
    name: process.env.APP_NAME || '在线学习平台',
    version: process.env.APP_VERSION || '1.0.0',
    port: parseInt(process.env.PORT) || 3000,
    host: process.env.HOST || '0.0.0.0',
    baseUrl: process.env.BASE_URL || 'http://localhost:3000',
    frontendUrl: process.env.FRONTEND_URL || 'http://localhost:8080'
  },

  // 环境配置
  env: process.env.NODE_ENV || 'development',
  
  // 数据库配置
  database: {
    host: process.env.DB_HOST,
    port: parseInt(process.env.DB_PORT) || 3306,
    database: process.env.DB_NAME,
    username: process.env.DB_USER,
    password: process.env.DB_PASSWORD || null,
    dialect: process.env.DB_DIALECT || 'mysql',
    storage: process.env.DB_DIALECT === 'sqlite' ? process.env.DB_NAME : undefined,
    timezone: process.env.DB_DIALECT === 'sqlite' ? undefined : '+08:00',
    logging: process.env.NODE_ENV === 'development' ? console.log : false,
    pool: {
      max: parseInt(process.env.DB_POOL_MAX) || 20,
      min: parseInt(process.env.DB_POOL_MIN) || 0,
      acquire: parseInt(process.env.DB_POOL_ACQUIRE) || 30000,
      idle: parseInt(process.env.DB_POOL_IDLE) || 10000
    },
    define: {
      timestamps: true,
      underscored: true,
      freezeTableName: true,
      charset: 'utf8mb4',
      collate: 'utf8mb4_unicode_ci'
    }
  },

  // Redis配置
  redis: {
    host: process.env.REDIS_HOST || 'localhost',
    port: parseInt(process.env.REDIS_PORT) || 6379,
    password: process.env.REDIS_PASSWORD || null,
    db: parseInt(process.env.REDIS_DB) || 0,
    keyPrefix: process.env.REDIS_KEY_PREFIX || 'rx:',
    retryDelayOnFailover: 100,
    enableReadyCheck: true,
    maxRetriesPerRequest: 3,
    lazyConnect: true,
    connectTimeout: 10000,
    commandTimeout: 5000
  },

  // JWT配置
  jwt: {
    secret: process.env.JWT_SECRET,
    expiresIn: process.env.JWT_EXPIRES_IN || '7d',
    refreshExpiresIn: process.env.JWT_REFRESH_EXPIRES_IN || '30d',
    issuer: process.env.JWT_ISSUER || 'rx-platform',
    audience: process.env.JWT_AUDIENCE || 'rx-users'
  },

  // 会话配置
  session: {
    secret: process.env.SESSION_SECRET,
    maxAge: parseInt(process.env.SESSION_MAX_AGE) || 24 * 60 * 60 * 1000, // 24小时
    name: process.env.SESSION_NAME || 'rx.sid'
  },

  // CORS配置
  cors: {
    origin: process.env.CORS_ORIGIN ? 
      process.env.CORS_ORIGIN.split(',').map(url => url.trim()) : 
      ['http://localhost:8080', 'http://localhost:3000', 'http://localhost:8081'],
    credentials: true
  },

  // 速率限制配置
  rateLimit: {
    windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000, // 15分钟
    max: parseInt(process.env.RATE_LIMIT_MAX) || 100, // 每个IP最大请求数
    skipSuccessfulRequests: false,
    skipFailedRequests: false
  },

  // 文件上传配置
  upload: {
    maxFileSize: parseInt(process.env.UPLOAD_MAX_FILE_SIZE) || 50 * 1024 * 1024, // 50MB
    allowedTypes: process.env.UPLOAD_ALLOWED_TYPES ? 
      process.env.UPLOAD_ALLOWED_TYPES.split(',').map(type => type.trim()) :
      ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'video/mp4', 'video/webm', 'application/pdf'],
    uploadDir: process.env.UPLOAD_DIR || path.join(process.cwd(), 'uploads'),
    publicDir: process.env.PUBLIC_DIR || path.join(process.cwd(), 'public')
  },

  // 邮件配置
  email: {
    host: process.env.EMAIL_HOST || 'smtp.gmail.com',
    port: parseInt(process.env.EMAIL_PORT) || 587,
    secure: process.env.EMAIL_SECURE === 'true',
    auth: {
      user: process.env.EMAIL_USER,
      pass: process.env.EMAIL_PASSWORD
    },
    from: process.env.EMAIL_FROM || 'noreply@rxbase.com',
    templates: {
      welcome: 'welcome',
      resetPassword: 'reset-password',
      verifyEmail: 'verify-email',
      courseEnrollment: 'course-enrollment',
      examResult: 'exam-result',
      certificate: 'certificate'
    }
  },

  // 短信配置
  sms: {
    provider: process.env.SMS_PROVIDER || 'aliyun', // aliyun, tencent, twilio
    accessKeyId: process.env.SMS_ACCESS_KEY_ID,
    accessKeySecret: process.env.SMS_ACCESS_KEY_SECRET,
    signName: process.env.SMS_SIGN_NAME || '在线学习平台',
    templates: {
      verification: process.env.SMS_TEMPLATE_VERIFICATION,
      resetPassword: process.env.SMS_TEMPLATE_RESET_PASSWORD,
      login: process.env.SMS_TEMPLATE_LOGIN
    }
  },

  // 支付配置
  payment: {
    alipay: {
      appId: process.env.ALIPAY_APP_ID,
      privateKey: process.env.ALIPAY_PRIVATE_KEY,
      publicKey: process.env.ALIPAY_PUBLIC_KEY,
      gateway: process.env.ALIPAY_GATEWAY || 'https://openapi.alipay.com/gateway.do',
      notifyUrl: process.env.ALIPAY_NOTIFY_URL,
      returnUrl: process.env.ALIPAY_RETURN_URL
    },
    wechat: {
      appId: process.env.WECHAT_APP_ID,
      mchId: process.env.WECHAT_MCH_ID,
      key: process.env.WECHAT_KEY,
      certPath: process.env.WECHAT_CERT_PATH,
      keyPath: process.env.WECHAT_KEY_PATH,
      notifyUrl: process.env.WECHAT_NOTIFY_URL
    }
  },

  // 云存储配置
  storage: {
    provider: process.env.STORAGE_PROVIDER || 'local', // local, aliyun, qcloud, aws
    aliyun: {
      accessKeyId: process.env.ALIYUN_ACCESS_KEY_ID,
      accessKeySecret: process.env.ALIYUN_ACCESS_KEY_SECRET,
      bucket: process.env.ALIYUN_BUCKET,
      region: process.env.ALIYUN_REGION || 'oss-cn-hangzhou',
      endpoint: process.env.ALIYUN_ENDPOINT
    },
    qcloud: {
      secretId: process.env.QCLOUD_SECRET_ID,
      secretKey: process.env.QCLOUD_SECRET_KEY,
      bucket: process.env.QCLOUD_BUCKET,
      region: process.env.QCLOUD_REGION || 'ap-guangzhou'
    },
    aws: {
      accessKeyId: process.env.AWS_ACCESS_KEY_ID,
      secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
      bucket: process.env.AWS_BUCKET,
      region: process.env.AWS_REGION || 'us-east-1'
    }
  },

  // 日志配置
  logging: {
    level: process.env.LOG_LEVEL || 'info',
    file: {
      enabled: process.env.LOG_FILE_ENABLED === 'true',
      filename: process.env.LOG_FILENAME || 'app.log',
      maxsize: parseInt(process.env.LOG_MAX_SIZE) || 10 * 1024 * 1024, // 10MB
      maxFiles: parseInt(process.env.LOG_MAX_FILES) || 5,
      datePattern: process.env.LOG_DATE_PATTERN || 'YYYY-MM-DD'
    },
    console: {
      enabled: process.env.LOG_CONSOLE_ENABLED !== 'false',
      colorize: process.env.LOG_COLORIZE !== 'false'
    }
  },

  // 缓存配置
  cache: {
    ttl: parseInt(process.env.CACHE_TTL) || 3600, // 1小时
    checkPeriod: parseInt(process.env.CACHE_CHECK_PERIOD) || 600, // 10分钟
    maxKeys: parseInt(process.env.CACHE_MAX_KEYS) || 1000
  },

  // 安全配置
  security: {
    bcryptRounds: parseInt(process.env.BCRYPT_ROUNDS) || 12,
    passwordMinLength: parseInt(process.env.PASSWORD_MIN_LENGTH) || 8,
    passwordMaxLength: parseInt(process.env.PASSWORD_MAX_LENGTH) || 128,
    maxLoginAttempts: parseInt(process.env.MAX_LOGIN_ATTEMPTS) || 5,
    lockoutTime: parseInt(process.env.LOCKOUT_TIME) || 15 * 60 * 1000, // 15分钟
    verificationCodeExpiry: parseInt(process.env.VERIFICATION_CODE_EXPIRY) || 5 * 60 * 1000, // 5分钟
    resetPasswordExpiry: parseInt(process.env.RESET_PASSWORD_EXPIRY) || 30 * 60 * 1000 // 30分钟
  },

  // 业务配置
  business: {
    // 课程配置
    course: {
      maxEnrollments: parseInt(process.env.COURSE_MAX_ENROLLMENTS) || 1000,
      defaultDuration: parseInt(process.env.COURSE_DEFAULT_DURATION) || 30, // 天
      allowPreview: process.env.COURSE_ALLOW_PREVIEW !== 'false',
      previewDuration: parseInt(process.env.COURSE_PREVIEW_DURATION) || 5 // 分钟
    },
    // 考试配置
    exam: {
      maxAttempts: parseInt(process.env.EXAM_MAX_ATTEMPTS) || 3,
      defaultDuration: parseInt(process.env.EXAM_DEFAULT_DURATION) || 60, // 分钟
      passingScore: parseInt(process.env.EXAM_PASSING_SCORE) || 60, // 百分比
      autoSubmit: process.env.EXAM_AUTO_SUBMIT !== 'false'
    },
    // 证书配置
    certificate: {
      validityPeriod: parseInt(process.env.CERTIFICATE_VALIDITY_PERIOD) || 365, // 天
      template: process.env.CERTIFICATE_TEMPLATE || 'default',
      watermark: process.env.CERTIFICATE_WATERMARK !== 'false'
    }
  },

  // 第三方服务配置
  thirdParty: {
    // 微信配置
    wechat: {
      appId: process.env.WECHAT_MINI_APP_ID,
      appSecret: process.env.WECHAT_MINI_APP_SECRET
    },
    // 钉钉配置
    dingtalk: {
      appKey: process.env.DINGTALK_APP_KEY,
      appSecret: process.env.DINGTALK_APP_SECRET
    },
    // 企业微信配置
    workwechat: {
      corpId: process.env.WORK_WECHAT_CORP_ID,
      agentId: process.env.WORK_WECHAT_AGENT_ID,
      secret: process.env.WORK_WECHAT_SECRET
    }
  },

  // 监控配置
  monitoring: {
    enabled: process.env.MONITORING_ENABLED === 'true',
    endpoint: process.env.MONITORING_ENDPOINT,
    apiKey: process.env.MONITORING_API_KEY,
    interval: parseInt(process.env.MONITORING_INTERVAL) || 60000 // 1分钟
  }
};

// 开发环境特殊配置
if (config.env === 'development') {
  config.database.logging = console.log;
  config.logging.level = 'debug';
}

// 生产环境特殊配置
if (config.env === 'production') {
  config.database.logging = false;
  config.logging.level = 'warn';
  config.security.bcryptRounds = 14;
}

// 测试环境特殊配置
if (config.env === 'test') {
  config.database.logging = false;
  config.logging.level = 'error';
  config.security.bcryptRounds = 4; // 加快测试速度
}

module.exports = config;